// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const userCollection = db.collection('user')
const likeCollection = db.collection('liker_liked')
const rightinfoCollection = db.collection('rightinfo')
const rightCollection = db.collection('right')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = event.openid
  let infoContent = {}
  let likeEachCount = 0
  let hasRight = false

  if (openid == wxContext.OPENID){
    await userCollection.where({
      _openid: openid
    }).get().then(res => {
      infoContent = res.data[0]
    })


    await rightinfoCollection.where({
      openid
    }).get().then(res => {
      let rightInfo = res.data[0]
      infoContent.birthday = rightInfo.birthday
      infoContent.address = rightInfo.address
      infoContent.emotion = rightInfo.emotion
      infoContent.school = rightInfo.school
      infoContent.company = rightInfo.company
      infoContent.chatway = rightInfo.chatway
    })

    return infoContent
  }

  await userCollection.where({
    _openid: openid
  }).get().then(res => {
    infoContent = res.data[0]
  })

  await likeCollection.where({
    likerOpenId: openid,
    likedOpenId: wxContext.OPENID
  }).count().then(res => {
    likeEachCount = res.total
  })

  await likeCollection.where({
    likerOpenId: wxContext.OPENID,
    likedOpenId: openid
  }).count().then(res => {
    likeEachCount = likeEachCount + res.total
  })

  infoContent.likeEachCount = likeEachCount

//检测是否互通
  await rightCollection.where({
    righter: wxContext.OPENID,
    righted: openid
  }).get().then(res => {
    if(res.data.length == 0){
      hasRight = false
    }else{
      hasRight = res.data[0].status == 2 ? true : false
    }
  })
  if(!hasRight){
    await rightCollection.where({
      righter: openid,
      righted: wxContext.OPENID
    }).get().then(res => {
      if (res.data.length == 0) {
        hasRight = false
      } else {
        hasRight = res.data[0].status == 2 ? true : false
      }
    })
  }

  if(hasRight){
    await rightinfoCollection.where({
      openid
    }).get().then(res => {
      let rightInfo = res.data[0]
      infoContent.birthday = rightInfo.birthdayState ? rightInfo.birthday : ''
      infoContent.address = rightInfo.addressState ? rightInfo.address : []
      infoContent.emotion = rightInfo.emotionState ? rightInfo.emotion : ''
      infoContent.school = rightInfo.schoolState ? rightInfo.school : ''
      infoContent.company = rightInfo.companyState ? rightInfo.company : ''
      infoContent.chatway = rightInfo.chatwayState ? rightInfo.chatway : ''
    })
  }

  return infoContent
}